package de.hauschild.gmltracer.gml.impl.control;

import de.hauschild.gmltracer.gml.Environment;
import de.hauschild.gmltracer.gml.TokenStack;
import de.hauschild.gmltracer.gml.impl.AbstractToken;
import de.hauschild.gmltracer.gml.impl.value.bool.BooleanToken;

/**
 * Takes two {@link FunctionToken} and a {@link BooleanToken}. If the value of
 * the {@link BooleanToken} is <code>true</code> the first {@link FunctionToken}
 * will be applied, the second {@link FunctionToken} otherwise.
 * 
 * @author Klaus Hauschild
 * @since 1.0.0
 */
public class IfToken extends AbstractToken {

  private static final ApplyToken APPLY_TOKEN = new ApplyToken();

  @SuppressWarnings("boxing")
  @Override
  public void evaluate(final Environment environment, final TokenStack tokenStack) {
    final FunctionToken elseFunction = tokenStack.pop(FunctionToken.class);
    final FunctionToken ifFunction = tokenStack.pop(FunctionToken.class);
    final BooleanToken bool = tokenStack.pop(BooleanToken.class);

    if (bool.getValue()) {
      ifFunction.evaluate(environment, tokenStack);
    } else {
      elseFunction.evaluate(environment, tokenStack);
    }

    APPLY_TOKEN.evaluate(environment, tokenStack);
  }

  @Override
  public String toString() {
    return "if"; //$NON-NLS-1$
  }
}
